import service from '@/api/request'
import config from './config'
import type { FormData, ResPermissionTree } from './page.type'

const PageApi = config.api

const pageApi = {
  // 获取菜单树
  getList: () => service.get<ResPermissionTree>(PageApi.GET_URL),
  // 新增
  create: (data: FormData) => service.post(PageApi.CREATE_URL, data),
  // 修改
  update: (data: FormData) => {
    const id = data.id as string
    // 构建发送数据，过滤掉不应该发送的字段
    // status 保持为字符串（ACTIVE/INACTIVE），不转换为数字
    const updateData: Partial<FormData> & { id: string } = {
      id,
      name: data.name,
      code: data.code ?? null,
      toCode: data.toCode ?? null,
      type: data.type,
      pid: data.pid ?? null,
      level: data.level,
      status: (data.status as 'ACTIVE' | 'INACTIVE' | null | undefined) || 'ACTIVE', // 确保为正确的枚举类型
      sort: data.sort ?? 0,
      // 注意：不发送 createdAt, updatedAt, children 字段
    }
    return service.put(`${PageApi.UPDATE_URL}/${id}`, updateData)
  },
  // 删除
  delete: (id: string) => service.delete(PageApi.DELETE_URL + `/${id}`),
  // 批量删除权限
  batchDelete: (ids: string[]) => service.delete(PageApi.DELETE_URL, { data: ids }),
}

export default pageApi
